//package com.uniriho.lxr0860_printer
//
//import android.Manifest
//import android.app.PendingIntent
//import android.content.BroadcastReceiver
//import android.content.Context
//import android.content.Intent
//import android.content.IntentFilter
//import android.content.pm.PackageManager
//import android.hardware.usb.UsbDevice
//import android.hardware.usb.UsbManager
//import android.os.Bundle
//import android.os.Environment
//import android.os.Parcelable
//import android.os.storage.StorageManager
//import android.util.Log
//import androidx.activity.ComponentActivity
//import androidx.core.app.ActivityCompat
//import androidx.core.content.ContextCompat
//import com.github.mjdev.libaums.UsbMassStorageDevice
//import com.github.mjdev.libaums.fs.FileSystem
//import com.uniriho.lxr0860_printer.Constant.ACTION_USB_PERMISSION
//import java.io.File
//import java.io.FileInputStream
//import java.io.FileNotFoundException
//import java.io.FileOutputStream
//import java.io.IOException
//import java.lang.reflect.Method
//
//
//class MainActivity : ComponentActivity() {
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//        usbFile = cFolder!!.createDirectory(fileName_zyqbqmmwjj)
//
//        if (ContextCompat.checkSelfPermission(
//                this,
//                Manifest.permission.MANAGE_EXTERNAL_STORAGE
//            ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
//                this,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE
//            ) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(
//                this,
//                Manifest.permission.READ_EXTERNAL_STORAGE
//            ) != PackageManager.PERMISSION_GRANTED
//        ) {
//            ActivityCompat.requestPermissions(
//                this,
//                arrayOf(
//                    Manifest.permission.MANAGE_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE
//                ),
//                101
//            )
//        }
//
//        // 请求权限，如果需要的话
//        permissionIntent =
//            PendingIntent.getBroadcast(this, 0, Intent(UsbPrinter.ACTION_USB_PERMISSION), 0)
//        usbManager = getSystemService(USB_SERVICE) as UsbManager
//
//        val filter = IntentFilter(UsbPrinter.ACTION_USB_PERMISSION)
//        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
//        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
//        filter.addAction(DeviceConnFactoryManager.ACTION_CONN_STATE)
//        registerReceiver(usbReceiver, filter)
//
//
//        var path = getStoragePath(this, true);
//        Log.i("zsm", "path=" + path);
//        var sourcePath = "/storage/emulated/0/test.docx";
//        var targetPath = "/storage/0000-0000/test.docx";
//        var isCopy = copyFile(sourcePath, targetPath);
//        Log.i("zsm", "copy file ret:" + isCopy);
//
//    }
//
//    var storageDevices: Array<UsbMassStorageDevice>? = null
//
//    /**
//     * 读取 USB设备列表
//     *
//     * @return USB设备列表
//     */
//    fun getDeviceList(): Array<UsbMassStorageDevice>? {
//        val usbManager = getSystemService(USB_SERVICE) as UsbManager
//        //获取存储设备
//        storageDevices = UsbMassStorageDevice.getMassStorageDevices(this)
//
//        val pendingIntent = PendingIntent.getBroadcast(this, 0, Intent(ACTION_USB_PERMISSION), 0)
//        //可能有几个 一般只有一个 因为大部分手机只有1个otg插口
//        for (device in storageDevices!!) {
////            Log.e(TAG, device.getUsbDevice().getDeviceName());
//            //有就直接读取设备是否有权限
//            if (!usbManager.hasPermission(device.usbDevice)) {
//                //没有权限请求权限
//                usbManager.requestPermission(device.usbDevice, pendingIntent)
//            }
//        }
//        return storageDevices
//    }
//
//
//    var usbPath: String? = null
//    var usbManager: UsbManager? = null
//    var usbReceiver: BroadcastReceiver? = null
//    var permissionIntent: PendingIntent? = null
//    private fun registerUsbReceiver() {
//        usbReceiver = object : BroadcastReceiver() {
//            override fun onReceive(context: Context, intent: Intent) {
//                val action = intent.action
//                if (UsbPrinter.ACTION_USB_PERMISSION == action) {
//                    synchronized(this) {
//                        val usbDevice =
//                            intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
//                        //                        UsbDeviceConnection mUsbDeviceConnection = usbManager.openDevice(usbDevice);
//                        if (usbManager!!.hasPermission(usbDevice)) {
//                            // 获取挂载路径
//                            Log.i(
//                                "zsm",
//                                Environment.getExternalStorageDirectory().absolutePath
//                            )
//                            for (file in File.listRoots()) {
//                                Log.i("zsm", file.absolutePath)
//                                if (file.absolutePath.startsWith(
//                                        Environment.getExternalStorageDirectory()
//                                            .absolutePath
//                                    )
//                                ) {
//                                    usbPath = file.absolutePath
//                                    break
//                                }
//                            }
//                            Log.i("zsm", "device:" + usbDevice!!.deviceName)
//                            if (usbPath == null) usbPath = "/storage/emulated/0"
//                            Log.i("zsm", "usbPath:$usbPath")
//                        }
//                    }
//                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED == action) {
//                    val mUsbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
//                    if (mUsbDevice != null) {
//                        Log.e("zsm", "有设备拔出")
//                    }
//                } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
//                    val mUsbDevice = intent.getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)
//                    Log.e("zsm", "有设备插入")
//                    if (mUsbDevice != null) {
//                        if (!usbManager!!.hasPermission(mUsbDevice)) {
//                            usbManager!!.requestPermission(mUsbDevice, permissionIntent)
//                        } else {
//                            runOnUiThread(Runnable {
//                                val devices =
//                                    UsbMassStorageDevice.getMassStorageDevices(this)
//                            })
////
////                            for (device in devices) {
////                                // before interacting with a device you need to call init()!
////                                device.init()
////                                // Only uses the first partition on the device
////                                val currentFs: FileSystem = device.partitions[0].fileSystem
////                                Log.d("zsm", "Capacity: " + currentFs.capacity)
////                                Log.d("zsm", "Occupied Space: " + currentFs.occupiedSpace)
////                                Log.d("zsm", "Free Space: " + currentFs.freeSpace)
////                                Log.d("zsm", "Chunk size: " + currentFs.chunkSize)
////                                val cFolder = currentFs.rootDirectory;
////                                Log.d("zsm", "folder: " + cFolder)
////                            }
//
//                        }
//                    }
//                }
//            }
//        }
//    }
//
//    fun copyFile(sourcePath: String, targetPath: String): Boolean {
//        val sourceFile = File(sourcePath)
//        val targetFile = File(targetPath)
//        if (!sourceFile.exists()) {
//            println("源文件不存在: $sourcePath")
//            return false
//        } else {
//            println("源文件存在: $sourcePath")
//        }
//        if (targetFile.exists()) {
//            println("目标文件已存在: $targetPath")
//            // 根据需要决定是否覆盖
//            // 这里我们选择删除已存在的目标文件，然后继续复制
//            if (!targetFile.delete()) {
//                println("无法删除已存在的目标文件: $targetPath")
//                return false
//            }
//        } else {
//            println("目标文件不存在: $targetPath")
//            targetFile.createNewFile()
//        }
//        try {
//            FileInputStream(sourceFile).use { fis ->
//                FileOutputStream(targetFile).use { fos ->
//                    val buffer = ByteArray(1024)
//                    var length: Int
//                    while (fis.read(buffer).also { length = it } > 0) {
//                        fos.write(buffer, 0, length)
//                    }
//                }
//            }
//            return true
//        } catch (e: FileNotFoundException) {
//            println("复制文件时发生错误: 文件未找到异常处理")
//            return false
//            // 文件未找到异常处理
//        } catch (e: IOException) {
//            println("复制文件时发生错误: ${e.message}")
//            return false
//        }
//    }
//
//    fun getStoragePath(context: Context, isUsb: Boolean): String? {
//        var path = ""
//        val mStorageManager = context.getSystemService(STORAGE_SERVICE) as StorageManager
//        val volumeInfoClazz: Class<*>
//        val diskInfoClaszz: Class<*>
//        try {
//            volumeInfoClazz = Class.forName("android.os.storage.VolumeInfo")
//            diskInfoClaszz = Class.forName("android.os.storage.DiskInfo")
//            val StorageManager_getVolumes: Method =
//                Class.forName("android.os.storage.StorageManager").getMethod("getVolumes")
//            val VolumeInfo_GetDisk: Method = volumeInfoClazz.getMethod("getDisk")
//            val VolumeInfo_GetPath: Method = volumeInfoClazz.getMethod("getPath")
//            val DiskInfo_IsUsb: Method = diskInfoClaszz.getMethod("isUsb")
//            val DiskInfo_IsSd: Method = diskInfoClaszz.getMethod("isSd")
//            val List_VolumeInfo = (StorageManager_getVolumes.invoke(mStorageManager) as List<Any>)!!
//            for (i in List_VolumeInfo!!.indices) {
//                val volumeInfo = List_VolumeInfo!![i]
//                val diskInfo: Any = VolumeInfo_GetDisk.invoke(volumeInfo) ?: continue
//                val file = VolumeInfo_GetPath.invoke(volumeInfo) as File
//                if (isUsb == DiskInfo_IsUsb.invoke(diskInfo)) { //usb
//                    assert(file != null)
//                    path = file!!.absolutePath
//                } else if (!isUsb == DiskInfo_IsSd.invoke(diskInfo)) { //sd
//                    assert(file != null)
//                    path = file!!.absolutePath
//                }
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
//        return path
//    }
//}